<?php

/**
 * contact : 刘经理 19326416371
 * company : 版权所属 四川北星惯牌科技有限公司
 **/

namespace app\common\manager\assistant;

use app\common\constant\Constant;
use app\common\library\InviteCode;
use app\common\library\Wechat;
use app\common\manager\BaseManager;
use app\common\manager\StatisticsManager;
use app\common\manager\StoreAccountManager;
use app\common\manager\UserAccountManager;
use app\common\model\assistant\Account;
use app\common\model\assistant\Assistant;
use app\common\model\assistant\Background;
use app\common\model\assistant\Bill;
use app\common\model\assistant\Order;
use app\common\model\assistant\Tags;
use app\common\model\assistant\Time;
use app\common\model\AssistantOrder;
use app\common\model\Config;
use app\common\model\Level;
use app\common\model\ProfitStatistics;
use app\common\model\RelationImage;
use app\common\model\Store;
use app\common\model\Team;
use app\common\model\User;
use app\common\model\UserTeam;
use think\Db;
use think\Exception;

class AssistantManager extends BaseManager
{

    /**
     * 申请助教入驻
     * @param User $user
     * @param $address
     * @param $latitude
     * @param $longitude
     * @param $gender
     * @param $avatar
     * @param bool $trans
     * @return array
     */
    public static function apply(User $user,$address,$latitude,$longitude,$gender,$avatar,bool $trans=true):array
    {
        if ($trans){
            Db::startTrans();
        }
        try {
            if ($user->is_authentication != \app\common\model\User::IS_AUTHENTICATION_YES){
                throw new Exception('您还未实名认证，无法申请入驻助教，请前往个人中心实名认证');
            }
            if ($user->is_assistant){
                throw new Exception('您已入驻助教，请勿重复操作');
            }

            $assistantInfo = Assistant::where('user_id',$user->id)->find();
            if (isset($assistantInfo) && $assistantInfo['review_status'] == Assistant::REVIEW_STATUS_WAIT){
                throw new Exception('您已申请助教，请勿重复操作，请等待工作人员审核');
            }

            if (isset($assistantInfo) && $assistantInfo['review_status'] == Assistant::REVIEW_STATUS_PASS){
                throw new Exception('您已成功申请助教，请勿重复操作');
            }

            if (isset($assistantInfo) && $assistantInfo['review_status'] == Assistant::REVIEW_STATUS_REJECT){
                $assistantInfo->review_status = Assistant::REVIEW_STATUS_WAIT;
                $assistantInfo->save();
            }else{
                if(!$assistantInfo = Assistant::create([
                    'user_id' => $user->id,
                    'address'=>$address,
                    'lat' => bcadd($latitude,0,7),
                    'lng' => bcadd($longitude,0,7),
                    'type' => Assistant::TYPE_PERSONAL,
                    'nickname' => $user->nickname,
                    'avatar' => $avatar ?? $user->avatar,
                    'gender' => $gender ?? $user->gender,
                    'birthday' => $user->birthday ?? '',
                    'level' => Level::order('all_count asc')->value('vl_id') ?? 1,
                    'create_time' => time(),
                    'update_time' => time()
                ])){
                    throw new Exception('申请失败，请稍后再试');
                }
            }
            if ($trans)
                Db::commit();
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
        }catch (Exception $exception){
            if ($trans){
                Db::rollback();
            }
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }

        return ['code'=>self::getStatusCode(),'message'=>self::getMessage()];
    }

    /**
     * 通过用户id 获取用户入驻信息
     * @param User $user 用户
     * @return array
     */
    public static function getApplyInfo(User $user):array
    {

        try {
            $assistantInfo = Assistant::where('user_id',$user->id)->field('review_status,reason')->order('id desc')->find();
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
            self::setData($assistantInfo);
        }catch (Exception $exception){
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData()];
    }


    public static function detail($assistantId):array
    {
        try {
                $assistantInfo = Assistant::where('id',$assistantId)->where('review_status',Assistant::REVIEW_STATUS_PASS)->field('id,user_id,type,store_id,nickname,order_switch,avatar,gender,birthday,assistant_price,time_unit,level,create_time,update_time,review_status,reason,introduce')->find();
                $backgroundList = Background::where('assistant_id',$assistantInfo['id'])->field('id,url,create_time')->order('id asc')->select();
                $timeList = Time::where('assistant_id',$assistantInfo['id'])->field('id,start_hours,end_hours,start_time,end_time,compare_start,compare_end,start_minute,end_minute,create_time,update_time')->order('start_time asc')->select();
                $assistantInfo['time_list'] = $timeList;
                $assistantInfo['background_list'] = $backgroundList;
                self::setStatusCode(self::$successCode);
                self::setMessage(self::$successMessage);
                self::setData($assistantInfo);
        }catch (Exception $exception){
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData()];
    }
    /**
     * 通过用户id 获取用户入驻信息
     * @param $user
     * @return array
     */
    public static function getAssistantInfo($user):array
    {
        try {
            $assistantInfo = Assistant::where('user_id',$user->id)->field('id,lat,lng,address,assistant_price,time_unit,user_id,type,store_id,nickname,order_switch,avatar,gender,birthday,level,create_time,update_time,review_status,reason,introduce,tags')->find();
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
            self::setData($assistantInfo);
        }catch (Exception $exception){
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData()];
    }

    /**
     * 编辑助教信息
     * @param $user
     * @param $data
     * @return array
     */
    public static function editAssistantInfo($user,$data):array {
        try {
            $assistantInfo = Assistant::where('user_id',$user->id)->find();
            if (isset($assistantInfo) && $assistantInfo['review_status'] == Assistant::REVIEW_STATUS_PASS){
                $assistantInfo->nickname = $data['nickname'];
                $assistantInfo->avatar = $data['avatar'];
                $assistantInfo->gender = $data['gender'];
                $assistantInfo->birthday = $data['birthday'];
                $assistantInfo->introduce = $data['introduce'];
                $assistantInfo->lat = $data['lat'];
                $assistantInfo->lng = $data['lng'];
                $assistantInfo->address = $data['address'];
                $assistantInfo->update_time = time();
                $assistantInfo->save();
                self::setStatusCode(self::$successCode);
                self::setMessage(self::$successMessage);
            }else{
                throw new Exception('您还未申请助教，请先申请助教');
            }
        }catch (Exception $exception){
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code'=>self::getStatusCode(),'message'=>self::getMessage()];
    }

    /**
     * 助教订单列表
     * @param $user
     * @param $status
     * @param $page
     * @param $step
     * @return array
     */
    public static function getOrderList($user,$status=-1,$page=1,$step=Constant::PAGE_LIMIT):array
    {
        $start = ($page-1)*$step;
        $return = ['total'=>0,'totalPage'=>1,'currentPage'=>$page,'list'=>[]];
        try {
            $orderModel = new Order();
            $count = $orderModel->alias('o')
                ->join('pay_order po','po.po_id = o.order_id','left')
                ->where('o.user_id',$user->id)
                ->where('o.pay_status','<>',Order::PAY_STATUS_INIT)
                ->where(function ($query) use($status){
                    if ($status != -1){
                        $query->where('o.status',$status);
                    }
                })
                ->count();

            $assistantList = $orderModel->alias('o')
                ->join('pay_order po','po.po_id = o.order_id','left')
                ->where('o.user_id',$user->id)
                ->where('o.pay_status','<>',Order::PAY_STATUS_INIT)
                ->where(function ($query) use($status){
                    if ($status != -1){
                        $query->where('o.status',$status);
                    }
                })
                ->field('o.id,o.order_id,o.status,o.orderer,o.order,o.create_time,o.amount,o.pay_status,o.order_start_time,o.order_end_time,o.server_start_time,o.server_end_time,o.real_amount,o.discount_amount,o.distance_amount,o.extends,po.type,po.relation_id,po.pay_date as pay_time_order')
                ->order('o.id desc')
                ->limit($start,$step)
                ->select();

            $teamModel = new Team();
            if ($assistantList){
                foreach ($assistantList as $k=>$v){
                    $assistantList[$k]['order_start_time'] = date('Y-m-d H:i:s',$v['order_start_time']);
                    $assistantList[$k]['order_end_time'] = date('Y-m-d H:i:s',$v['order_end_time']);
                    $assistantList[$k]['server_start_time'] = date('Y-m-d H:i:s',$v['server_start_time']);
                    $assistantList[$k]['server_end_time'] = date('Y-m-d H:i:s',$v['server_end_time']);
                    $assistantList[$k]['create_time'] = date('Y-m-d H:i:s',$v['create_time']);
                    $assistantList[$k]['pay_time_order'] = date('Y-m-d H:i:s',$v['pay_time_order']);
                    $assistantList[$k]['status_name'] = Order::getStatusName($v['status'],$orderModel->getStatusList());
                    $assistantList[$k]['pay_status_name'] = Order::getPayStatusName($v['pay_status'],$orderModel->getPayStatusList());
                    $assistantList[$k]['orderer_info'] = User::where('id',$v['orderer'])->field('id,nickname,mobile,avatar,gender,birthday')->find() ?? [];
                    $teamInfo = [];
                    if ($v->type == \app\common\model\Order::TYPE_TEAM){
                        $teamInfo = $teamModel->alias('t')->join('relation_image ri','ri.relation_id = t.t_id','inner')
                            ->where('ri.type',RelationImage::TYPE_TEAM)
                            ->where('t.t_id',$v['relation_id'])->field('t.t_id,t.number_people,t.join_number,t.title,t.start_date,t.end_date,ri.url')->find() ?? [];
                    }
                    $assistantList[$k]['relation_info'] = $teamInfo ?? [];
                    $extends = [];
                    if ($v->extends){
                        $extends = unserialize($v['extends']);
                    }
                    $assistantList[$k]['extends'] = $extends;
                }
            }
            $pageData = page($count,$step,$page);
            $return['list'] = $assistantList;
            $return = array_merge($return,$pageData);

            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
            self::setData($return);
        }catch (Exception $exception){
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData()];
    }

    /**
     * 用户助教订单列表
     * @param $user
     * @param $status
     * @param $page
     * @param $step
     * @return array
     */
    public static function getUserOrderList($user,$status=-1,$page=1,$step=Constant::PAGE_LIMIT):array
    {
        $start = ($page-1)*$step;
        $return = ['total'=>0,'totalPage'=>1,'currentPage'=>$page,'list'=>[]];
        try {
            $orderModel = new AssistantOrder();
            $count = $orderModel->alias('o')
                ->join('pay_order po','po.po_id = o.order_id','left')
                ->where('o.user_id',$user->id)
                ->where('o.pay_status','<>',Order::PAY_STATUS_INIT)
                ->where(function ($query) use($status){
                    if ($status != -1){
                        $query->where('o.status',$status);
                    }
                })
                ->count();

            $assistantList = $orderModel->alias('o')
                ->join('pay_order po','po.po_id = o.order_id','left')
                ->where('o.user_id',$user->id)
                ->where('o.pay_status','<>',Order::PAY_STATUS_INIT)
                ->where(function ($query) use($status){
                    if ($status != -1){
                        $query->where('o.status',$status);
                    }
                })
                ->field('o.id,o.order_id,o.assistant_id,o.status,o.order,o.create_time,o.amount,o.pay_status,o.order_start_time,o.order_end_time,o.server_start_time,o.server_end_time,o.real_amount,o.discount_amount,o.distance_amount,o.extends,po.type,po.relation_id,po.pay_date as pay_time_order')
                ->order('o.id desc')
                ->limit($start,$step)
                ->select();

            $teamModel = new Team();
            if ($assistantList){
                foreach ($assistantList as $k=>$v){
                    $assistantList[$k]['order_start_time'] = date('Y-m-d H:i:s',$v['order_start_time']);
                    $assistantList[$k]['order_end_time'] = date('Y-m-d H:i:s',$v['order_end_time']);
                    $assistantList[$k]['server_start_time'] = date('Y-m-d H:i:s',$v['server_start_time']);
                    $assistantList[$k]['server_end_time'] = date('Y-m-d H:i:s',$v['server_end_time']);
                    $assistantList[$k]['create_time'] = date('Y-m-d H:i:s',$v['create_time']);
                    $assistantList[$k]['pay_time_order'] = date('Y-m-d H:i:s',$v['pay_time_order']);
                    $assistantList[$k]['status_name'] = Order::getStatusName($v['status'],$orderModel->getStatusList());
                    $assistantList[$k]['pay_status_name'] = Order::getPayStatusName($v['pay_status'],$orderModel->getPayStatusList());
                    $teamInfo = [];
                    if ($v->type == \app\common\model\Order::TYPE_TEAM){
                        $teamInfo = $teamModel->alias('t')->join('relation_image ri','ri.relation_id = t.t_id','inner')
                            ->where('ri.type',RelationImage::TYPE_TEAM)
                            ->where('t.t_id',$v['relation_id'])->field('t.t_id,t.number_people,t.join_number,t.title,t.start_date,t.end_date,ri.url')->find() ?? [];
                    }
                    $assistantList[$k]['relation_info'] = $teamInfo ?? [];
                    $extends = [];
                    if ($v->extends){
                        $extends = unserialize($v['extends']);
                    }
                    $assistantInfo = [];
                    if ($v->assistant_id){
                        $assistantInfo = Assistant::where('id',$v['assistant_id'])->field('nickname,avatar,gender,birthday,level,introduce')->find();
                    }
                    $assistantList[$k]['extends'] = $extends;
                    $assistantList[$k]['assistant_info'] = $assistantInfo;
                }
            }
            $pageData = page($count,$step,$page);
            $return['list'] = $assistantList;
            $return = array_merge($return,$pageData);

            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
            self::setData($return);
        }catch (Exception $exception){
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData()];
    }

    /**
     * 订单开始
     * @param $user
     * @param $order_id
     * @param $trans
     * @return array
     */
    public static function setOrderStart($user,$order_id,$trans=true):array
    {
        if($trans){
            Db::startTrans();
        }
        try {
            $orderModel = new Order();
            $orderInfo = $orderModel->where('id',$order_id)->where('assistant_id',$user->assistant_id)->where('user_id',$user->id)->find();
            if (isset($orderInfo) && $orderInfo['status'] == Order::STATUS_WAIT && $orderInfo['pay_status'] == Order::PAY_STATUS_YES){

                if($orderInfo['order_start_time'] > time()){
                    throw new Exception('订单开始时间还未到，请正确操作');
                }
                $orderInfo->status = Order::STATUS_START;
                $orderInfo->server_start_time = time();
                $orderInfo->update_time = time();
                $orderInfo->save();

                $assistantOrderModel = new AssistantOrder();
                $assistantOrder = $assistantOrderModel->where('user_id',$orderInfo['orderer'])->where('order_id',$orderInfo['order_id'])->where('assistant_id',$orderInfo['assistant_id'])->find();
                if ($assistantOrder){
                    $assistantOrder->status = $assistantOrderModel::STATUS_START;
                    $assistantOrder->server_start_time = time();
                    $assistantOrder->update_time = time();
                    $assistantOrder->save();
                }


                if (!Assistant::where('id',$user->assistant_id)->where('user_id',$user->id)->where('status',Assistant::STATUS_ENABLE)->where('review_status',Assistant::REVIEW_STATUS_PASS)->update(['in_service'=>Assistant::IN_SERVICE_STATUS_ON,'update_time'=>time()])){
                    throw new Exception('订单状态异常，请刷新后重试');
                }
                if ($trans)
                    Db::commit();
                self::setStatusCode(self::$successCode);
                self::setMessage(self::$successMessage);
            }else{
                throw new Exception('订单状态异常，请刷新后重试');
            }
        }catch (Exception $exception) {
            if ($trans)
                Db::rollback();
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code' => self::getStatusCode(),'message' => self::getMessage()];
    }

    /**
     * 订单结束
     * @param $user
     * @param $order_id
     * @param $trans
     * @return array
     */

    public static function setOrderEnd($user,$order_id,$trans=true):array
    {
        if ($trans){
            Db::startTrans();
        }
        try {
            $orderModel = new Order();
            $orderInfo = $orderModel->where('id',$order_id)->where('assistant_id',$user->assistant_id)->where('user_id',$user->id)->find();
            if (isset($orderInfo) && $orderInfo['status'] == Order::STATUS_START && $orderInfo['pay_status'] == Order::PAY_STATUS_YES){
                $orderInfo->status = Order::STATUS_END;
                $orderInfo->server_end_time = time();
                $orderInfo->update_time = time();
                $orderInfo->save();
                if($orderInfo['order_end_time'] > time()){
                    throw new Exception('订单还未结束，当前不能结束订单');
                }
                if (!Assistant::where('id',$user->assistant_id)->where('user_id',$user->id)->where('status',Assistant::STATUS_ENABLE)->where('review_status',Assistant::REVIEW_STATUS_PASS)->update(['in_service'=>Assistant::IN_SERVICE_STATUS_OFF,'update_time'=>time()])){
                    throw new Exception('订单状态异常，请刷新后重试');
                }

                if (!Account::where('assistant_id',$user->assistant_id)->where('user_id',$user->id)->update([
                    'order_num'=>Db::raw('order_num + 1'),
                    'update_time'=>time()
                ])){
                    throw new Exception('订单状态异常，请刷新后重试');
                }

                $assistantOrderModel = new AssistantOrder();
                $assistantOrder = $assistantOrderModel->where('order_id',$orderInfo['order_id'])->where('user_id',$orderInfo['orderer'])->where('assistant_id',$orderInfo['assistant_id'])->find();
                if ($assistantOrder){
                    $assistantOrder->status = $assistantOrderModel::STATUS_END;
                    $assistantOrder->server_end_time = time();
                    $assistantOrder->update_time = time();
                    $assistantOrder->save();
                }

                $money = 0;
                $assistantRate = Config::where('name','assistant_rate')->value('value');
                if ($assistantRate > 0){
                    $userInfo = User::where('id',$user->id)->field('id,invited_user_id,invited_store_id')->find();
                    if ($userInfo['invited_user_id']){
                        $money = bcdiv(bcmul(bcsub($orderInfo['real_amount'],$orderInfo['discount_amount'],2) ,$assistantRate,2),100,2);
                        $resultTotal = UserAccountManager::money($userInfo['invited_user_id'],$money,UserAccountManager::CHANGE_TYPE_INCOME,time(),UserAccountManager::TYPE_ASSISTANT_REWARD,['relation_id'=>$orderInfo['id'],'relation_order'=>$orderInfo['order']],false);
                        if ($resultTotal['code']!=UserAccountManager::$successCode){
                            throw new Exception($resultTotal['message']);
                        }
                    }else if ($userInfo['invited_store_id']){
                        $money = bcdiv(bcmul(bcsub($orderInfo['real_amount'],$orderInfo['discount_amount'],2) ,$assistantRate,2),100,2);
                        $storeInfo = Store::where('id', $user->invited_store_id)->find();
                        $storeAccountResult = StoreAccountManager::money($storeInfo['merchant_id'],$userInfo['invited_store_id'],$money,StoreAccountManager::CHANGE_TYPE_INCOME,time(),StoreAccountManager::TYPE_ASSISTANT_REWARD,['relation_id'=>$orderInfo['id'],'relation_order'=>$orderInfo['order']]);
                        if ($storeAccountResult['code'] != StoreAccountManager::$successCode){
                            throw new Exception('上级分成失败，请刷新后重试');
                        }

                        $result = StatisticsManager::enter($storeInfo['merchant_id'],$user->invited_store_id,$money,time(),ProfitStatistics::TYPE_ASSISTANT_REWARD,StatisticsManager::TYPE_PROFIT,false);
                        if ($result['code'] != StatisticsManager::$successCode){
                            throw new Exception($result['message']);
                        }
                    }

                }
                $assistantMoney = bcsub(bcsub($orderInfo['real_amount'],$orderInfo['discount_amount'],2),$money,2);
                $storeRateMoney = 0;
                $assistantInfo = Assistant::where('id',$user->assistant_id)->where('user_id',$user->id)->find();
                if ($assistantInfo['type'] == Assistant::TYPE_STORE && $assistantInfo['store_id']){
                    $assistantStoreInfo = Store::where('id', $assistantInfo['store_id'])->find();
                    if ($assistantStoreInfo && $assistantStoreInfo['assistant_rate']){
                        $storeRateMoney = bcdiv(bcmul($assistantMoney ,$assistantStoreInfo['assistant_rate'],2),100,2);
                        $storeResult = StoreAccountManager::money($assistantStoreInfo['merchant_id'],$assistantInfo['store_id'],$storeRateMoney,StoreAccountManager::CHANGE_TYPE_INCOME,time(),StoreAccountManager::TYPE_ASSISTANT,['relation_id'=>$orderInfo['id'],'relation_order'=>$orderInfo['order']]);
                        if ($storeResult['code'] != StoreAccountManager::$successCode){
                            throw new Exception('门店分成失败，请刷新后重试');
                        }

                        $result = StatisticsManager::enter($assistantStoreInfo['merchant_id'],$assistantInfo['store_id'],$storeRateMoney,time(),ProfitStatistics::TYPE_ASSISTANT_REBATE,StatisticsManager::TYPE_PROFIT,false);
                        if ($result['code'] != StatisticsManager::$successCode){
                            throw new Exception($result['message']);
                        }
                    }
                }
                $assistantMoney = bcsub($assistantMoney,$storeRateMoney,2);
                /**
                 * 路费结算
                 */
                $result = AssistantAccountManager::money($user->assistant_id,$user->id,$assistantMoney,AssistantAccountManager::CHANGE_TYPE_INCOME,time(),AssistantAccountManager::TYPE_TEAM,['relation_id'=>$orderInfo['id'],'relation_order'=>$orderInfo['order']]);
                if ($result['code'] != AssistantAccountManager::$successCode){
                    throw new Exception('账户入账失败，请刷新后重试');
                }

                $billResult = self::assistantBill($user->assistant_id,$user->id,$assistantMoney,time(),false);
                if ($billResult['code'] != self::$successCode){
                    throw new Exception('账单生成失败，请刷新后重试');
                }

                if ($trans)
                    Db::commit();
                self::setStatusCode(self::$successCode);
                self::setMessage(self::$successMessage);
            }else{
                throw new Exception('订单状态异常，请刷新后重试');
            }
        }catch (Exception $exception) {
            if ($trans)
                Db::rollback();
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code' => self::getStatusCode(),'message' => self::getMessage()];
    }

    /**
     * 接受订单
     * @param $user
     * @param $order_id
     * @param $trans
     * @return array
     */
    public static function acceptOrder($user,$order_id,$trans=true):array
    {
        if ($trans){
            Db::startTrans();
        }
        try {
            $orderModel = new Order();
            $orderInfo = $orderModel->where('id',$order_id)->where('user_id',$user->id)->find();

            if (isset($orderInfo) && $orderInfo['status'] == Order::STATUS_INIT && $orderInfo['pay_status'] == Order::PAY_STATUS_YES){
                $payOrderInfo = \app\common\model\Order::where('po_id',$orderInfo['order_id'])->where('pay_state',\app\common\model\Order::PAY_STATE_SUCCESS)->find();
                if (!$payOrderInfo){
                    throw new Exception('订单状态异常，请刷新后重试');
                }

                $orderInfo->status = Order::STATUS_WAIT;
                $orderInfo->save();

                $assistantOrderModel = new AssistantOrder();
                if($payOrderInfo['type'] == \app\common\model\Order::TYPE_ASSISTANT){
                    $assistantOrder = $assistantOrderModel->where('order_id',$orderInfo['order_id'])->find();
                    if ($assistantOrder){
                        $assistantOrder->status = $assistantOrderModel::STATUS_WAIT;
                        $assistantOrder->update_time = time();
                        $assistantOrder->save();
                    }
                }else if($payOrderInfo['type'] == \app\common\model\Order::TYPE_TEAM){
                    $assistantOrder = $assistantOrderModel->where('user_id',$orderInfo['orderer'])->where('assistant_id',$orderInfo['assistant_id'])->where('order_id',$orderInfo['order_id'])->find();
                    if ($assistantOrder){
                        $assistantOrder->status = $assistantOrderModel::STATUS_WAIT;
                        $assistantOrder->update_time = time();
                        $assistantOrder->save();
                    }

                    $invite = new InviteCode();
                    $inviteCode = $invite->enCode();
                    if(!$payOrder = \app\common\model\Order::create([
                        'order' => orderNum(),
                        'user_id' => $user->id,
                        'pay_state' => \app\common\model\Order::PAY_STATE_SUCCESS,
                        'order_money' => 0,
                        'pref_money' => 0,
                        'real_money' => 0,
                        'type' => \app\common\model\Order::TYPE_TEAM,
                        'relation_id' => $payOrderInfo['relation_id'],
                        'is_balance' => \app\common\model\Order::IS_BALANCE_YES,
                        'ct_date' => time(),
                        'up_date' => time(),
                    ])){
                        throw new Exception('订单创建失败');
                    }

                    if(!$userTeam = UserTeam::create([
                        'user_id'=>$user->id,
                        'team'=>$payOrderInfo['relation_id'],
                        'verif_code'=>$inviteCode,
                        'state'=>UserTeam::STATE_SUCCESS,
                        'pay_state'=>UserTeam::PAY_STATUS_SUCCESS,
                        'order_id'=>$payOrder['po_id'],
                        'ct_date'=>time(),
                        'up_date'=>time(),
                    ])){
                        throw new Exception('组队成员创建失败');
                    }

                    if (!Team::where('t_id',$payOrderInfo['relation_id'])->setInc('join_number')){
                        throw new Exception('组队人数更新失败');
                    }
                }


                if ($trans)
                    Db::commit();
                self::setStatusCode(self::$successCode);
                self::setMessage(self::$successMessage);
            }else{
                throw new Exception('订单状态异常，请刷新后重试');
            }
        }catch (Exception $exception) {
            if ($trans)
                Db::rollback();
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage().$exception->getLine());
        }
        return ['code' => self::getStatusCode(),'message' => self::getMessage()];
    }

    /**
     * 拒绝订单
     * @param $user
     * @param $order_id
     * @param $trans
     * @return array
     */
    public static function refundOrder($user,$order_id,$trans=true):array
    {
        if ($trans){
            Db::startTrans();
        }
        try {
            $orderModel = new Order();
            $orderInfo = $orderModel->where('id',$order_id)->where('user_id',$user->id)->find();
            if (isset($orderInfo) && $orderInfo['status'] < Order::STATUS_START && $orderInfo['pay_status'] == Order::PAY_STATUS_YES){

                $payOrderInfo = \app\common\model\Order::where('po_id',$orderInfo['order_id'])->where('pay_state',\app\common\model\Order::PAY_STATE_SUCCESS)->find();
                if (!$payOrderInfo){
                    throw new Exception('订单状态异常，请刷新后重试');
                }

                $refundAmount = bcadd($orderInfo['real_amount'],0,2);
                $refundResult = UserAccountManager::money($orderInfo['orderer'],$refundAmount,UserAccountManager::CHANGE_TYPE_INCOME,time(),UserAccountManager::TYPE_REFUND,['relation_id'=>$orderInfo['order_id'],'relation_order'=>$orderInfo['order']],false);
                if ($refundResult['code'] != UserAccountManager::$successCode){
                    throw new Exception('退款失败，请刷新后重试');
                }

                $assistantOrderModel = new AssistantOrder();
                $assistantOrder = $assistantOrderModel->where('order_id',$orderInfo['order_id'])->where('user_id',$orderInfo['orderer'])->where('assistant_id',$orderInfo['assistant_id'])->find();
                if ($assistantOrder){
                    $assistantOrder->status = $assistantOrderModel::STATUS_REFUND;
                    $assistantOrder->refund_type = $assistantOrderModel::REFUND_TYPE_ASSISTANT;
                    $assistantOrder->save();
                }
                $title = '';
                $order = $payOrderInfo['order'];
                $date  = date('Y-m-d H:i:s',time());
                if($payOrderInfo['type'] == \app\common\model\Order::TYPE_ASSISTANT){
                    $payOrderInfo->pay_state = \app\common\model\Order::PAY_STATE_CANCEL;
                    $payOrderInfo->cancel_date = time();
                    $payOrderInfo->up_date = time();
                    $payOrderInfo->save();
                    $title = Assistant::where('id',$orderInfo['assistant_id'])->value('nickname');
                    $page = 'page_main/views/teamDetails?id='.$payOrderInfo['relation_id'];
                }else if($payOrderInfo['type'] == \app\common\model\Order::TYPE_TEAM){
                    $title = Team::where('t_id',$payOrderInfo['relation_id'])->value('title');
                    $page = 'pages/main/main';
                    $userTeam = UserTeam::where('user_id', $user->id)
                        ->where('team', $payOrderInfo['relation_id'])
                        ->where('state', UserTeam::STATE_SUCCESS)
                        ->where('pay_state', UserTeam::PAY_STATUS_SUCCESS)
                        ->find();
                    if ($userTeam) {
                        $userTeam->pay_state = UserTeam::PAY_STATUS_REFUND;
                        $userTeam->up_date = time();
                        $userTeam->save();
                        if (!\app\common\model\Order::where('po_id',$userTeam['order_id'])->where('pay_state',\app\common\model\Order::PAY_STATE_SUCCESS)->update(['pay_state'=>\app\common\model\Order::PAY_STATE_CANCEL,'cancel_date'=>time()])){
                            throw new Exception('组队订单取消失败');
                        }
                        if (!Team::where('t_id', $payOrderInfo['relation_id'])->update(['join_number'=>Db::raw('join_number = join_number - 1'), 'ordered_number'=>Db::raw('ordered_number = ordered_number - 1')])) {
                            throw new Exception('组队人数更新失败');
                        }
                    } else {
                        if (!Team::where('t_id', $payOrderInfo['relation_id'])->setDec('ordered_number')) {
                            throw new Exception('组队人数更新失败');
                        }
                    }
                }



                $orderInfo->refund_type = Order::REFUND_TYPE_ASSISTANT;
                $orderInfo->status = Order::STATUS_REFUND;
                $orderInfo->pay_status = Order::PAY_STATUS_REFUND;
                $orderInfo->server_end_time = time();
                $orderInfo->save();

                /**
                 * 微信消息通知
                 */
                $params['title'] = $title ?? '组队消息';
                $params['date'] = $date;
                $params['order'] = $order;
                $params['noticer'] = '平台通知';
                $openId = User::where('id',$payOrderInfo['user_id'])->value('open_id');
                if ($openId){
                    $wechat = new Wechat();
                    $result = $wechat->publishMsg($openId,$params,Wechat::TEMPLATE_ID_USER_ASSISTANT_REFUND,$page);
                }

                if ($trans)
                    Db::commit();
                self::setStatusCode(self::$successCode);
                self::setMessage(self::$successMessage);
            }else {
                throw new Exception('订单状态异常，请刷新后重试');
            }
        }catch (Exception $exception) {
            if ($trans)
                Db::rollback();
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code' => self::getStatusCode(),'message' => self::getMessage()];
    }

    /**
     * 用户拒绝订单
     * @param $user
     * @param $order_id
     * @param $trans
     * @return array
     */
    public static function refundUserOrder($user,$order_id,$trans=true):array
    {
        if ($trans){
            Db::startTrans();
        }
        try {
            $orderModel = new AssistantOrder();
            $orderInfo = $orderModel->where('id',$order_id)->where('user_id',$user->id)->find();
            if (isset($orderInfo) && $orderInfo['status'] < Order::STATUS_START && $orderInfo['pay_status'] == Order::PAY_STATUS_YES){

                $payOrderInfo = \app\common\model\Order::where('po_id',$orderInfo['order_id'])->where('pay_state',\app\common\model\Order::PAY_STATE_SUCCESS)->find();
                if (!$payOrderInfo){
                    throw new Exception('订单状态异常，请刷新后重试');
                }

                $refundAmount = bcadd($orderInfo['real_amount'],0,2);
                $refundResult = UserAccountManager::money($orderInfo['user_id'],$refundAmount,UserAccountManager::CHANGE_TYPE_INCOME,time(),UserAccountManager::TYPE_ASSISTANT_REFUND,['relation_id'=>$orderInfo['order_id'],'relation_order'=>$orderInfo['order']],false);
                if ($refundResult['code'] != UserAccountManager::$successCode){
                    throw new Exception('退款失败，请刷新后重试');
                }
                $assistantOrderModel = new Order();
                $assistantOrder = $assistantOrderModel->where('order_id',$orderInfo['order_id'])->where('orderer',$orderInfo['user_id'])->where('assistant_id',$orderInfo['assistant_id'])->find();
                if ($assistantOrder){
                    $assistantOrder->status = $assistantOrderModel::STATUS_REFUND;
                    $assistantOrder->refund_type = $assistantOrderModel::REFUND_TYPE_USER;
                    $assistantOrder->save();
                }
                $order = $payOrderInfo['order'];

                if($payOrderInfo['type'] == \app\common\model\Order::TYPE_ASSISTANT){
                    $payOrderInfo->pay_state = \app\common\model\Order::PAY_STATE_CANCEL;
                    $payOrderInfo->cancel_date = time();
                    $payOrderInfo->up_date = time();
                    $payOrderInfo->save();
                    $page = 'page_main/views/teamDetails?id='.$payOrderInfo['relation_id'];
                }else if($payOrderInfo['type'] == \app\common\model\Order::TYPE_TEAM){
                    $page = 'pages/main/main';
                    $userTeam = UserTeam::where('user_id', $assistantOrder->user_id)
                        ->where('team', $payOrderInfo['relation_id'])
                        ->where('state', UserTeam::STATE_SUCCESS)
                        ->where('pay_state', UserTeam::PAY_STATUS_SUCCESS)
                        ->find();
                    if ($userTeam) {
                        $userTeam->pay_state = UserTeam::PAY_STATUS_REFUND;
                        $userTeam->up_date = time();
                        $userTeam->save();

                        if (!\app\common\model\Order::where('po_id',$userTeam['order_id'])->where('pay_state',\app\common\model\Order::PAY_STATE_SUCCESS)->update(['pay_state'=>\app\common\model\Order::PAY_STATE_CANCEL,'cancel_date'=>time()])){
                            throw new Exception('组队订单取消失败');
                        }

                        if (!Team::where('t_id', $payOrderInfo['relation_id'])->update(['join_number'=>Db::raw('join_number = join_number - 1'), 'ordered_number'=>Db::raw('ordered_number = ordered_number - 1')])) {
                            throw new Exception('组队人数更新失败');
                        }
                    } else {
                        if (!Team::where('t_id', $payOrderInfo['relation_id'])->setDec('ordered_number')) {
                            throw new Exception('组队人数更新失败');
                        }
                    }
                }
                $params['order'] = $order;
                $params['notice'] = '请前往助教中心订单详情，查看详情';
                $params['reason'] = '用户主动取消订单';
                $openId = User::where('id',$assistantOrder->user_id)->value('open_id');
                if ($openId){
                    $wechat = new Wechat();
                    $result = $wechat->publishMsg($openId,$params,Wechat::TEMPLATE_ID_ASSISTANT_USER__REFUND,$page);
                }

                $orderInfo->refund_type = Order::REFUND_TYPE_USER;
                $orderInfo->status = Order::STATUS_REFUND;
                $orderInfo->pay_status = Order::PAY_STATUS_REFUND;
                $orderInfo->server_end_time = time();
                $orderInfo->save();
                if ($trans)
                    Db::commit();
                self::setStatusCode(self::$successCode);
                self::setMessage(self::$successMessage);
            }else {
                throw new Exception('订单状态异常，请刷新后重试');
            }
        }catch (Exception $exception) {
            if ($trans)
                Db::rollback();
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code' => self::getStatusCode(),'message' => self::getMessage()];
    }

    /**
     * 获取助教图片
     * @param $user
     * @param $page
     * @param $step
     * @return array
     */
    public static function getAssistantImage($user,$page=1,$step=Constant::PAGE_LIMIT):array
    {
        try {
            $start = ($page-1)*$step;
            $return = ['total'=>0,'totalPage'=>1,'currentPage'=>$page,'list'=>[]];
            $imageModel = new Background();
            $count = $imageModel->where('user_id',$user->id)->count();
            $imageList = $imageModel->where('user_id',$user->id)->field('id,url')->order('id desc')->limit($start,$step)->select();
            if ($imageList){
                foreach ($imageList as $k=>$v){
                    if ($v['url'] && strpos($v['url'],'http') === false){
                        $imageList[$k]['url'] = cdnurl($v['url']);
                    }
                }
            }
            $pageData = page($count,$step,$page);
            $return['list'] = $imageList;
            $return = array_merge($return,$pageData);
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
            self::setData($return);
        }catch (Exception $exception){
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData()];
    }


    public static function AssistantImages($assistant_id,$page=1,$step=Constant::PAGE_LIMIT):array
    {
        try {
            $start = ($page-1)*$step;
            $return = ['total'=>0,'totalPage'=>1,'currentPage'=>$page,'list'=>[]];
            $imageModel = new Background();
            $count = $imageModel->where('assistant_id',$assistant_id)->count();
            $imageList = $imageModel->where('assistant_id',$assistant_id)->field('id,url')->order('id desc')->limit($start,$step)->select();
            if ($imageList){
                foreach ($imageList as $k=>$v){
                    if ($v['url'] && strpos($v['url'],'http') === false){
                        $imageList[$k]['url'] = cdnurl($v['url']);
                    }
                }
            }
            $pageData = page($count,$step,$page);
            $return['list'] = $imageList;
            $return = array_merge($return,$pageData);
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
            self::setData($return);
        }catch (Exception $exception){
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData()];
    }

    /**
     * 添加助教图片
     * @param $user
     * @param $url
     * @param $trans
     * @return array
     */
    public static function addAssistantImage($user,$url,$trans=true)
    {
        if ($trans){
            Db::startTrans();
        }
        try {
             $imageModel = new Background();
             $imageModel->user_id = $user->id;
             $imageModel->url = $url;
             $imageModel->assistant_id = $user->assistant_id;
             $imageModel->create_time = time();
             $imageModel->save();
             if ($trans)
                 Db::commit();
             self::setStatusCode(self::$successCode);
             self::setMessage(self::$successMessage);
             self::setData(['id' => $imageModel->id ]);
        }catch (Exception $exception) {
            if ($trans)
                Db::rollback();
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code' => self::getStatusCode(),'message' => self::getMessage(),'data'=>self::getData()];
    }

    /**
     * 删除助教图片
     * @param $user
     * @param $id
     * @param $trans
     * @return array
     */
    public static function deleteAssistantImage($user,$id,$trans=true)
    {
        if ($trans){
            Db::startTrans();
        }
        try {
            $imageModel = new Background();
            $imageModel->where('id',$id)->where('user_id',$user->id)->where('assistant_id',$user->assistant_id)->delete();
            if ($trans)
                Db::commit();
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
        }catch (Exception $exception) {
            if ($trans)
                Db::rollback();
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code' => self::getStatusCode(),'message' => self::getMessage()];
    }

    /**
     * 助教接单开关
     * @param User $user
     * @param $status
     * @param $trans
     * @return array
     */
    public static function orderSwitch(User $user,$status,$trans=true):array
    {
        if ($trans) {
            Db::startTrans();
        }
        try {
            $assistantModel = new Assistant();
            $assistantInfo = $assistantModel->where('id',$user->assistant_id)->where('user_id', $user->id)->find();
            if (!$assistantInfo) {
                throw new Exception('助教信息不存在');
            }

            if ($assistantInfo['status'] != Assistant::STATUS_ENABLE) {
                throw new Exception('助教状态异常');
            }

            if ($assistantInfo['review_status'] != Assistant::REVIEW_STATUS_PASS){
                throw new Exception('当前未通过审核，无法进行操作');
            }

            $time = Time::where('assistant_id',$user->assistant_id)->where('status',Time::STATUS_NORMAL)->find();
            if (!$time && $status == Assistant::ORDER_SWITCH_ON){
                throw new Exception('当前接单时间段未设置');
            }

            if ($assistantInfo['order_switch'] == $status){
                throw new Exception('当前状态已是'.Assistant::getOrderSwitchName($status,$assistantModel->getOrderSwitchList()));
            }

            $assistantInfo->order_switch = $status;
            $assistantInfo->update_time = time();
            $assistantInfo->save();

            if ($trans) {
                Db::commit();
            }
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
        } catch (Exception $exception) {
            if ($trans)
                Db::rollback();
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code' => self::getStatusCode(),'message' => self::getMessage(),'data'=>self::getData()];
    }

    /**
     * 获取助教列表
     * @param $user
     * @param $status
     * @param $recommend
     * @param $lng
     * @param $lat
     * @param $radius
     * @param $page
     * @param $step
     * @return array
     */
    public static function getAssistantList($user=null,$status=null,$recommend=null,$lng=0.0,$lat=0.00,$radius=100,$page=1,$step=Constant::PAGE_LIMIT):array
    {
        try {
            $h = intval(date('H',time()));
            $i = date('i',time());
            $compare = $h.$i;
            $start = ($page-1)*$step;

            $distance = null;
            if ($lng && $lat){
                $distance = getDistance($lat,$lng,$radius);
            }
            $where = [];
            if (!is_null($status)){
                if ($status == 1){
                    $where['a.in_service'] = Assistant::IN_SERVICE_STATUS_ON;
                }else if ($status == 2){
                    $where['a.in_service'] = Assistant::IN_SERVICE_STATUS_OFF;
                }
            }

            if ($recommend && $recommend == Assistant::RECOMMEND_STATUS_YES){
                $where['a.recommend'] = Assistant::RECOMMEND_STATUS_YES;
            }

            $return = ['total'=>0,'totalPage'=>1,'currentPage'=>$page,'list'=>[]];
            $assistantModel = new Assistant();
            $count = $assistantModel->alias('a')
                ->join('assistant_time t','a.id = t.assistant_id','inner')
                ->where(function ($query) use ($user){
                    if (!empty($user)){
                        $query->where('a.user_id','<>',$user->id);
                    }
                })
                ->where(function ($query) use ($where){
                    if ($where) {
                        $query->where($where);
                    }
                })
                ->where('a.order_switch',Assistant::ORDER_SWITCH_ON)
                ->where('a.review_status',Assistant::REVIEW_STATUS_PASS)
                ->where('t.compare_start','<=',$compare)
                ->where('t.compare_end','>=',$compare)
                ->where('t.status',Time::STATUS_NORMAL)
                ->where(function ($query) use($distance){
                    if ($distance){
                        if (!empty($distance['minLat']) && !empty($distance['maxLat']) && !empty($distance['minLng']) && !empty($distance['maxLng'])){
                            return $query->where('a.lat','between',[$distance['minLat'],$distance['maxLat']])
                                ->where('a.lng','between',[$distance['minLng'],$distance['maxLng']]);
                        }
                    }
                })
                ->group('a.id')
                ->count();

            if($distance){
                $field = 'a.id,a.user_id,a.nickname,a.avatar,a.gender,a.birthday,a.order_switch,a.in_service,a.level,a.introduce,a.type,a.store_id,a.assistant_price,a.time_unit,a.show_order_num,a.address,a.`lat`,a.`lng`,(st_distance(point(a.`lng`,a.`lat`),point('.$lng.','.$lat.'))*111195/1000 ) as juli';
            }else{
                $field = 'a.id,a.user_id,a.nickname,a.avatar,a.gender,a.birthday,a.order_switch,a.in_service,a.level,a.introduce,a.type,a.store_id,a.assistant_price,a.time_unit,a.show_order_num + c.order_num as order_num,a.address,a.`lat`,a.`lng`,0.00 as juli';
            }
            $assistantList = $assistantModel->alias('a')
                ->join('assistant_time t','a.id = t.assistant_id','inner')
                ->join('assistant_account c','a.id = c.assistant_id','left')
                ->where(function ($query) use ($user){
                    if (!empty($user)){
                        $query->where('a.user_id','<>',$user->id);
                    }
                })
                ->where(function ($query) use ($where){
                    if ($where) {
                        $query->where($where);
                    }
                })
                ->where('a.order_switch',Assistant::ORDER_SWITCH_ON)
                ->where('a.review_status',Assistant::REVIEW_STATUS_PASS)
                ->where('t.compare_start','<=',$compare)
                ->where('t.compare_end','>',$compare)
                ->where('t.status',Time::STATUS_NORMAL)
                ->where(function ($query) use($distance){
                    if ($distance){
                        if (!empty($distance['minLat']) && !empty($distance['maxLat']) && !empty($distance['minLng']) && !empty($distance['maxLng'])){
                            return $query->where('a.lat','between',[$distance['minLat'],$distance['maxLat']])
                                ->where('a.lng','between',[$distance['minLng'],$distance['maxLng']]);
                        }
                    }
                })
                ->field($field)
                ->group('a.id')
                ->limit($start,$step)
                ->select();

            //echo $assistantModel->getLastSql();
            if ($assistantList){
                foreach ($assistantList as $k=>$v){
                    $assistantList[$k]['avatar'] = cdnurl($v['avatar']);
                    $assistantList[$k]['type_name'] = Assistant::getTypeName($v['type'],$assistantModel->getTypeList());
                    $assistantList[$k]['level_name'] = Level::where('vl_id',$v['level'])->value('vip_name') ?? '';
                    $assistantList[$k]['order_switch_name'] = Assistant::getOrderSwitchName($v['order_switch'],$assistantModel->getOrderSwitchList());
                }
            }
            $pageData = page($count,$step,$page);
            $return['list'] = $assistantList;
            $return = array_merge($return,$pageData);
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
            self::setData($return);
        }catch (Exception $exception){
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData()];
    }


    /**
     * 获取助教列表
     * @param $user
     * @param $status
     * @param $recommend
     * @param $lng
     * @param $lat
     * @param $radius
     * @param $page
     * @param $step
     * @return array
     */
    public static function getAssistantListCopy($user=null,$status=null,$recommend=null,$lng=0.0,$lat=0.00,$radius=100,$page=1,$step=Constant::PAGE_LIMIT):array
    {
        try {
            $h = intval(date('H',time()));
            $i = date('i',time());
            $compare = $h.$i;
            $start = ($page-1)*$step;

            $distance = null;
            if ($lng && $lat){
                $distance = getDistance($lat,$lng,$radius);
            }
            $where = [];
            if (!is_null($status)){
                if ($status == 1){
                    $where['a.in_service'] = Assistant::IN_SERVICE_STATUS_ON;
                }else if ($status == 2){
                    $where['a.in_service'] = Assistant::IN_SERVICE_STATUS_OFF;
                    $where['a.order_switch'] = Assistant::ORDER_SWITCH_ON;
                    $where['t.compare_start'] = ['<=',$compare];
                    $where['t.compare_end'] = ['>',$compare];
                }
            }

            if ($recommend && $recommend == Assistant::RECOMMEND_STATUS_YES){
                $where['a.recommend'] = Assistant::RECOMMEND_STATUS_YES;
            }

            $return = ['total'=>0,'totalPage'=>1,'currentPage'=>$page,'list'=>[]];
            $assistantModel = new Assistant();
            $count = $assistantModel->alias('a')
                ->join('assistant_time t','a.id = t.assistant_id','inner')
                ->where(function ($query) use ($user){
                    if (!empty($user)){
                        $query->where('a.user_id','<>',$user->id);
                    }
                })
                ->where(function ($query) use ($where){
                    if ($where) {
                        $query->where($where);
                    }
                })
                ->where('a.order_switch',Assistant::ORDER_SWITCH_ON)
                ->where('a.review_status',Assistant::REVIEW_STATUS_PASS)
                ->where('t.status',Time::STATUS_NORMAL)
                ->where(function ($query) use($distance){
                    if ($distance){
                        if (!empty($distance['minLat']) && !empty($distance['maxLat']) && !empty($distance['minLng']) && !empty($distance['maxLng'])){
                            return $query->where('a.lat','between',[$distance['minLat'],$distance['maxLat']])
                                ->where('a.lng','between',[$distance['minLng'],$distance['maxLng']]);
                        }
                    }
                })
                ->group('a.id')
                ->count();

            if($distance){
                $field = 't.compare_start,t.compare_end,a.recommend,a.id,a.user_id,a.nickname,a.avatar,a.gender,a.birthday,a.order_switch,a.tags,a.in_service,a.level,a.introduce,a.type,a.store_id,a.assistant_price,a.time_unit,a.show_order_num + c.order_num as order_num,a.address,a.`lat`,a.`lng`,(st_distance(point(a.`lng`,a.`lat`),point('.$lng.','.$lat.'))*111195/1000 ) as juli';
            }else{
                $field = 't.compare_start,t.compare_end,a.recommend,a.id,a.user_id,a.nickname,a.avatar,a.gender,a.birthday,a.order_switch,a.tags,a.in_service,a.level,a.introduce,a.type,a.store_id,a.assistant_price,a.time_unit,a.show_order_num + c.order_num as order_num,a.address,a.`lat`,a.`lng`,0.00 as juli';
            }
            $assistantList = $assistantModel->alias('a')
                ->join('assistant_time t','a.id = t.assistant_id','inner')
                ->join('assistant_account c','a.id = c.assistant_id','left')
                ->where(function ($query) use ($user){
                    if (!empty($user)){
                        $query->where('a.user_id','<>',$user->id);
                    }
                })
                ->where(function ($query) use ($where){
                    if ($where) {
                        $query->where($where);
                    }
                })
                ->where('a.review_status',Assistant::REVIEW_STATUS_PASS)
                ->where('t.status',Time::STATUS_NORMAL)
                ->where(function ($query) use($distance){
                    if ($distance){
                        if (!empty($distance['minLat']) && !empty($distance['maxLat']) && !empty($distance['minLng']) && !empty($distance['maxLng'])){
                            return $query->where('a.lat','between',[$distance['minLat'],$distance['maxLat']])
                                ->where('a.lng','between',[$distance['minLng'],$distance['maxLng']]);
                        }
                    }
                })
                ->field($field)
                ->group('a.id')
                ->order('a.order_switch desc,order_num desc')
                ->limit($start,$step)
                ->select();

            //echo $assistantModel->getLastSql();
            if ($assistantList){
                foreach ($assistantList as $k=>$v){
                    $assistantList[$k]['avatar'] = cdnurl($v['avatar']);
                    $assistantList[$k]['type_name'] = Assistant::getTypeName($v['type'],$assistantModel->getTypeList());
                    $assistantList[$k]['level_name'] = Level::where('vl_id',$v['level'])->value('vip_name') ?? '';
                    $assistantList[$k]['order_switch_name'] = Assistant::getOrderSwitchName($v['order_switch'],$assistantModel->getOrderSwitchList());
                    if ($v['compare_start'] <= $compare && $v['compare_end'] > $compare){
                        $assistantList[$k]['compare_status'] = 1;
                    }else{
                        $assistantList[$k]['compare_status'] = 0;
                    }
                }
            }
            $pageData = page($count,$step,$page);
            $return['list'] = $assistantList;
            $return = array_merge($return,$pageData);
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
            self::setData($return);
        }catch (Exception $exception){
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData()];
    }

    /**
     * 设置接单时间
     * @param $user
     * @param $startTime
     * @param $endTime
     * @param $trans
     * @return array
     */
    public static function setTime($user,$startTime,$endTime,$trans=true):array
    {
        if ($trans) {
            Db::startTrans();
        }
        try {
            $assistantModel = new Assistant();
            $assistantInfo = $assistantModel->where('id',$user->assistant_id)->where('user_id', $user->id)->find();
            if (!$assistantInfo) {
                throw new Exception('助教信息不存在');
            }

            if ($assistantInfo['status'] != Assistant::STATUS_ENABLE) {
                throw new Exception('助教状态异常');
            }

            if ($assistantInfo['review_status'] != Assistant::REVIEW_STATUS_PASS){
                throw new Exception('当前未通过审核，无法进行操作');
            }

            $startArr = explode(':',$startTime);
            $endArr = explode(':',$endTime);

            if($startArr[0] > 24 || $startArr[0] < 0 || $startArr[1] > 59 || $startArr[1] < 0){
                throw new Exception('开始时间格式错误');
            }

            if($endArr[0] > 24 || $endArr[0] < 0 || $endArr[1] > 59 || $endArr[1] < 0){
                throw new Exception('结束时间格式错误');
            }

            if ($startArr[0] > $endArr[0]){
                throw new Exception('开始时间不能大于结束时间');
            }
            if ($startArr[0] == $endArr[0] && $startArr[1] >= $endArr[1]){
                throw new Exception('开始时间不能大于结束时间');
            }

            $assistantTimeModel = new Time();
            $assistantTimeModel->assistant_id = $assistantInfo['id'];
            $assistantTimeModel->user_id = $user->id;
            $assistantTimeModel->start_hours = $startArr[0];
            $assistantTimeModel->start_minute = $startArr[1];
            $assistantTimeModel->end_hours = $endArr[0];
            $assistantTimeModel->end_minute = $endArr[1];
            $assistantTimeModel->start_time = $startTime;
            $assistantTimeModel->compare_start = $startArr[0].$startArr[1];
            $assistantTimeModel->compare_end = $endArr[0].$endArr[1];
            $assistantTimeModel->end_time = $endTime;
            $assistantTimeModel->create_time = time();
            $assistantTimeModel->update_time = time();
            $assistantTimeModel->save();

            if ($trans) {
                Db::commit();
            }
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
        } catch (Exception $exception) {
            if ($trans)
                Db::rollback();
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code' => self::getStatusCode(),'message' => self::getMessage()];
    }

    /**
     * 接单时间修改
     * @param $user
     * @param $startTime
     * @param $endTime
     * @param $id
     * @param $trans
     * @return array
     */
    public static function editTime($user,$startTime,$endTime,$id,$trans=true):array
    {
        if ($trans) {
            Db::startTrans();
        }
        try {
            $assistantModel = new Assistant();
            $assistantInfo = $assistantModel->where('id',$user->assistant_id)->where('user_id', $user->id)->find();
            if (!$assistantInfo) {
                throw new Exception('助教信息不存在');
            }

            if ($assistantInfo['status'] != Assistant::STATUS_ENABLE) {
                throw new Exception('助教状态异常');
            }

            if ($assistantInfo['review_status'] != Assistant::REVIEW_STATUS_PASS){
                throw new Exception('当前未通过审核，无法进行操作');
            }

            $assistantTimeModel = new Time();
            $assistantTimeInfo = $assistantTimeModel->where('id',$id)->where('assistant_id',$assistantInfo['id'])->where('user_id',$user->id)->where('status',Time::STATUS_NORMAL)->find();
            if (!$assistantTimeInfo) {
                throw new Exception('时间信息不存在');
            }

            $startArr = explode(':',$startTime);
            $endArr = explode(':',$endTime);
            if($startArr[0] > 24 || $startArr[0] < 0 || $startArr[1] > 59 || $startArr[1] < 0){
                throw new Exception('开始时间格式错误');
            }

            if($endArr[0] > 24 || $endArr[0] < 0 || $endArr[1] > 59 || $endArr[1] < 0){
                throw new Exception('结束时间格式错误');
            }

            if ($startArr[0] > $endArr[0]){
                throw new Exception('开始时间不能大于结束时间');
            }
            if ($startArr[0] == $endArr[0] && $startArr[1] >= $endArr[1]){
                throw new Exception('开始时间不能大于结束时间');
            }

            $assistantTimeInfo->start_hours = intval($startArr[0]);
            $assistantTimeInfo->start_minute = intval($startArr[1]);
            $assistantTimeInfo->end_hours = intval($endArr[0]);
            $assistantTimeInfo->end_minute = intval($endArr[1]);
            $assistantTimeInfo->compare_start = $startArr[0].$startArr[1];
            $assistantTimeInfo->compare_end = $endArr[0].$endArr[1];
            $assistantTimeInfo->start_time = $startTime;
            $assistantTimeInfo->end_time = $endTime;
            $assistantTimeInfo->update_time = time();
            $assistantTimeInfo->save();

            if ($trans) {
                Db::commit();
            }
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
        } catch (Exception $exception) {
            if ($trans)
                Db::rollback();
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code' => self::getStatusCode(),'message' => self::getMessage()];
    }

    /**
     * 删除接单时间
     * @param $user
     * @param $id
     * @param $trans
     * @return array
     */
    public static function deleteTime($user,$id,$trans=true):array
    {
        if ($trans) {
            Db::startTrans();
        }
        try {
            $assistantModel = new Assistant();
            $assistantInfo = $assistantModel->where('id',$user->assistant_id)->where('user_id', $user->id)->find();
            if (!$assistantInfo) {
                throw new Exception('助教信息不存在');
            }

            if ($assistantInfo['status'] != Assistant::STATUS_ENABLE) {
                throw new Exception('助教状态异常');
            }

            if ($assistantInfo['review_status'] != Assistant::REVIEW_STATUS_PASS){
                throw new Exception('当前未通过审核，无法进行操作');
            }

            $assistantTimeModel = new Time();
            $assistantTimeInfo = $assistantTimeModel->where('id',$id)->where('assistant_id',$assistantInfo['id'])->where('user_id',$user->id)->where('status',Time::STATUS_NORMAL)->find();
            if (!$assistantTimeInfo) {
                throw new Exception('时间信息不存在');
            }
            $assistantTimeInfo->delete();

            if ($trans) {
                Db::commit();
            }
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
        } catch (Exception $exception) {
            if ($trans)
                Db::rollback();
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code' => self::getStatusCode(),'message' => self::getMessage()];
    }

    public static function timeList($user,$page=1,$step=Constant::PAGE_LIMIT):array
    {
        $start = ($page-1)*$step;
        $return = ['total'=>0,'totalPage'=>1,'currentPage'=>$page,'list'=>[]];
        try {
            $assistantTimeBModel = new Time();
            $count = $assistantTimeBModel
                ->where('assistant_id',$user->assistant_id)
                ->where('user_id',$user->id)
                ->where('status',Time::STATUS_NORMAL)
                ->count();

            $assistantTimeList = $assistantTimeBModel
                ->where('assistant_id',$user->assistant_id)
                ->where('user_id',$user->id)
                ->where('status',Time::STATUS_NORMAL)
                ->field('id,start_hours,start_minute,end_hours,end_minute,status')
                ->limit($start,$step)
                ->select();

            $pageData = page($count,$step,$page);
            $return['list'] = $assistantTimeList;
            $return = array_merge($return,$pageData);
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
            self::setData($return);
        }catch (Exception $exception){
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData()];
    }

    /**
     * 助教账单
     * @param $assistantId
     * @param $userId
     * @param $amount
     * @param $date
     * @param $trans
     * @return array
     */
    public static function assistantBill($assistantId,$userId,$amount,$date,$trans=true):array
    {
        if ($trans) {
            Db::startTrans();
        }
        try {
            $assistantBillModel = new Bill();
            $year = date('Y',$date);
            $month = date('m',$date);
            $day = date('d',$date);
            /**
             * 今日数据更新或插入
             */
            $dayInfo = $assistantBillModel->where('type',Bill::TYPE_DAY)
                ->where('assistant_id',$assistantId)
                ->where('user_id',$userId)
                ->where('year',$year)
                ->where('month',$month)
                ->where('day',$day)
                ->find();
            if (!$dayInfo){
                $insertId = $assistantBillModel->insertGetId([
                    'type'=>Bill::TYPE_DAY,
                    'assistant_id'=>$assistantId,
                    'user_id'=>$userId,
                    'year'=>$year,
                    'month'=>$month,
                    'day'=>$day,
                    'amount'=>$amount,
                    'create_time'=>time(),
                    'update_time'=>time(),
                ]);

                if (!$insertId){
                    throw new Exception('今日数据插入失败');
                }

            }else{
                if(!$assistantBillModel->where('type',Bill::TYPE_DAY)
                    ->where('assistant_id',$assistantId)
                    ->where('user_id',$userId)
                    ->where('year',$year)
                    ->where('month',$month)
                    ->where('day',$day)
                    ->update(['amount'=>Db::raw('amount + '.$amount),'update_time'=>time()])){
                    throw new Exception('今日数据更新失败');
                }

            }

            /**
             * 当月数据更新或插入
             */
            $MonthInfo = $assistantBillModel->where('type',Bill::TYPE_MONTH)
                ->where('assistant_id',$assistantId)
                ->where('user_id',$userId)
                ->where('year',$year)
                ->where('month',$month)
                ->find();
            if (!$MonthInfo){
                $insertId = $assistantBillModel->insertGetId([
                    'type'=>Bill::TYPE_MONTH,
                    'assistant_id'=>$assistantId,
                    'user_id'=>$userId,
                    'year'=>$year,
                    'month'=>$month,
                    'amount'=>$amount,
                    'create_time'=>time(),
                    'update_time'=>time(),
                ]);

                if (!$insertId){
                    throw new Exception('本月数据插入失败');
                }

            }else{
                if(!$assistantBillModel->where('type',Bill::TYPE_MONTH)
                    ->where('assistant_id',$assistantId)
                    ->where('user_id',$userId)
                    ->where('year',$year)
                    ->where('month',$month)
                    ->update(['amount'=>Db::raw('amount + '.$amount),'update_time'=>time()])){
                    throw new Exception('本月数据更新失败');
                }

            }


            /**
             * 本年度数据更新或插入
             */
            $yearInfo = $assistantBillModel->where('type',Bill::TYPE_YEAR)
                ->where('assistant_id',$assistantId)
                ->where('user_id',$userId)
                ->where('year',$year)
                ->find();
            if (!$yearInfo){
                $insertId = $assistantBillModel->insertGetId([
                    'type'=>Bill::TYPE_YEAR,
                    'assistant_id'=>$assistantId,
                    'user_id'=>$userId,
                    'year'=>$year,
                    'amount'=>$amount,
                    'create_time'=>time(),
                    'update_time'=>time(),
                ]);

                if (!$insertId){
                    throw new Exception('本年度数据插入失败');
                }

            }else{
                if(!$assistantBillModel->where('type',Bill::TYPE_YEAR)
                    ->where('assistant_id',$assistantId)
                    ->where('user_id',$userId)
                    ->where('year',$year)
                    ->update(['amount'=>Db::raw('amount + '.$amount),'update_time'=>time()])){
                    throw new Exception('本年度数据更新失败');
                }

            }
            if ($trans)
                Db::commit();
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
        }catch (Exception $exception){
            if ($trans)
                Db::rollback();
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }

        return ['code' => self::getStatusCode(),'message' => self::getMessage()];
    }

    /**
     * 获取助教账户信息
     * @param $assistantId
     * @param $userId
     * @return array
     */
    public static function getAccount($assistantId,$userId):array
    {
        try {
            $return = AssistantAccountManager::getAccount($assistantId,$userId);
            if ($return['code'] != AssistantAccountManager::$successCode){
                throw new Exception($return['message']);
            }
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
            self::setData($return['data']);
        }catch (Exception $exception) {
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code' => self::getStatusCode(),'message' => self::getMessage(),'data'=>self::getData()];
    }

    /**
     * 检测助教是否可以组队
     * @param $assistantIds
     * @param $userId
     * @param $numbers
     * @param $startTime
     * @param $endTime
     * @return array
     */
    public static function checkAssistant($assistantIds,$userId,$numbers,$startTime,$endTime):array
    {
        try {
            $assistantIdsArr = explode(',', $assistantIds);
            if (count($assistantIdsArr) > ($numbers - 1)) {
                throw new Exception('助教数量不能大于组队人数');
            }
            $h = intval(date('H', time()));
            $i = date('i', time());
            $compare = $h . $i;
            $assistantModel = new Assistant();
            $assistantList = $assistantModel->alias('a')
                ->join('assistant_time t', 't.assistant_id = a.id', 'inner')
                ->where('a.id', 'in', $assistantIdsArr)
                ->where('a.user_id', '<>', $userId)
                ->where('t.compare_start', '<=', $compare)
                ->where('t.compare_end', '>=', $compare)
                ->where('a.status', Assistant::STATUS_ENABLE)
                ->where('a.review_status', Assistant::REVIEW_STATUS_PASS)
                ->where('a.order_switch', Assistant::ORDER_SWITCH_ON)
                ->where('a.in_service', Assistant::IN_SERVICE_STATUS_OFF)
                ->field('a.id,a.user_id,a.nickname,a.avatar,a.gender,a.birthday,a.order_switch,a.in_service,a.level,a.introduce,a.type,a.store_id,a.assistant_price,a.time_unit')
                ->group('a.id')
                ->select();
            if (count($assistantList) != count($assistantIdsArr)) {
                throw new Exception('助教信息有误，请重新选择');
            }
            foreach ($assistantList as $assistant) {

                if ($assistant->user_id == $userId) {
                    throw new Exception('助教不能是自己');
                }
                $info = \app\common\model\assistant\Order::where('assistant_id', $assistant['id'])
                    ->where('status', '<>', \app\common\model\assistant\Order::STATUS_END)
                    ->where('pay_status', \app\common\model\assistant\Order::PAY_STATUS_YES)
                    ->select();
                if ($info) {
                    foreach ($info as $order) {
                        if ($order['status'] == \app\common\model\assistant\Order::STATUS_REFUND && $order['pay_status'] == \app\common\model\assistant\Order::PAY_STATUS_REFUND) {
                            continue;
                        }
                        if ($order['order_start_time'] <= $startTime && $order['order_end_time'] >= $startTime) {
                            throw new Exception($assistant['nickname'] . '助教已有订单，无法参与');
                        } else if ($order['order_start_time'] <= $endTime && $order['order_end_time'] >= $endTime) {
                            throw new Exception($assistant['nickname'] . '助教已有订单，无法参与');
                        }
                    }
                }
            }
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
        }catch (Exception $exception) {
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code' => self::getStatusCode(),'message' => self::getMessage(),'data'=>self::getData()];
    }

    public static function getTags()
    {
        try {
            $tagModel = new Tags();
            $tagList = $tagModel->select();
            if (!$tagList){
                throw new Exception('标签信息不存在');
            }
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
            self::setData($tagList);
        }catch (Exception $exception){
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code' => self::getStatusCode(),'message' => self::getMessage(),'data'=>self::getData()];
    }

    public static function setTags($assistantId,$tags){
        try {
            $tagsArr = explode(',',$tags);
            if(count($tagsArr) > 5){
                throw new Exception('标签不能超过5个');
            }
            $assistantModel = new Assistant();
            $assistantInfo = $assistantModel->where('id',$assistantId)->find();
            if (!$assistantInfo){
                throw new Exception('助教信息不存在');
            }
            $assistantInfo->tags = implode(',',$tagsArr);
            $assistantInfo->save();
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
        }catch (Exception $exception){
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code' => self::getStatusCode(),'message' => self::getMessage()];
    }
}